package com.qianseit.westore.activity.account;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.MediaStore.Images;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.qianseit.westore.AgentApplication;
import com.qianseit.westore.BaseDoFragment;
import com.qianseit.westore.LoginedUser;
import com.qianseit.westore.Run;
import com.qianseit.westore.SimpleAnimListener;
import com.qianseit.westore.activity.AgentActivity;
import com.qianseit.westore.activity.MainTabFragmentActivity;
import com.qianseit.westore.http.JsonRequestBean;
import com.qianseit.westore.http.JsonRequestBean.JsonRequestCallback;
import com.qianseit.westore.http.JsonTask;
import com.qianseit.westore.http.JsonTaskHandler;
import com.qianseit.westore.ui.CustomDialog;
import com.qianseit.westore.util.Util;
import com.qianseit.westore.util.loader.FileUtils;
import com.beautymiracle.androidclient.R;

public class AccountHomeFragment extends BaseDoFragment {
	private static final int REQUEST_CODE_PICKER_AVATAR = 0x1001;

	private boolean fromLoginPage = false;

	private ListView mListView;

	private LoginedUser mLoginedUser;
	private ArrayList<ItemBeam> mItems = new ArrayList<ItemBeam>();
	private String walletAccount;

	private HomeItemAdapter mAdapter;
	private View mWallpaperPickerView;

	public AccountHomeFragment() {
		super();
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mLoginedUser = AgentApplication.getLoginedUser(mActivity);

		// mItems.add(new ItemBeam(R.drawable.me_item_orders,
		// R.string.me_item_orders, AgentActivity.FRAGMENT_ACCOUNT_ORDERS));
		mItems.add(new ItemBeam(R.drawable.me_item_balance,
				R.string.me_item_balance, 0));
		// mItems.add(new ItemBeam(R.drawable.me_item_collect,
		// R.string.me_item_collect, AgentActivity.FRAGMENT_FAVORITE_GOODS));
		// mItems.add(new ItemBeam(R.drawable.me_item_score,
		// R.string.me_item_score, AgentActivity.FRAGMENT_MYSCORE));
		// mItems.add(new ItemBeam(R.drawable.me_item_coupon,
		// R.string.me_item_coupon, AgentActivity.FRAGMENT_TICKET_LIST));
		// mItems.add(new ItemBeam(R.drawable.me_item_address,
		// R.string.me_item_address, AgentActivity.FRAGMENT_ADDRESS_BOOK));
		// mItems.add(new ItemBeam(R.drawable.me_item_shop,
		// R.string.me_item_shop,
		// AgentActivity.FRAGMENT_SHOP_SERVICE));
		// mItems.add(new ItemBeam(R.drawable.me_item_help,
		// R.string.me_item_help,
		// AgentActivity.FRAGMENT_HELP_CENTRE));
		mItems.add(new ItemBeam(R.drawable.me_item_orders,
				R.string.me_item_orders, AgentActivity.FRAGMENT_ACCOUNT_ORDERS));
		mItems.add(new ItemBeam(R.drawable.me_item_coupon,
				R.string.me_item_coupon, AgentActivity.FRAGMENT_TICKET_LIST));
		mItems.add(new ItemBeam(0, R.string.feedback,
				AgentActivity.FRAGMENT_FEEDBACK));
	}

	@Override
	public void onResume() {
		super.onResume();

//		if (!mLoginedUser.isLogined() && !fromLoginPage) {
//			mActivity.finish() ;
//		}
		
		initAccountHeaderView(rootView, mLoginedUser);
		if (!mLoginedUser.isLogined() && !fromLoginPage) {
			startActivityForResult(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_ACCOUNT_LOGIN),
					REQUEST_CODE_USER_LOGIN);
		} else {
			new JsonTask().execute(new GetWallet());
		}
		fromLoginPage = false;
	}

	public void init(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mActionBar.setTitle(R.string.tabbar_title4);
		mActionBar.setShowHomeView(false);
		mActionBar.getRightButton().setBackgroundResource(
				R.drawable.account_header_view_setting);
		mActionBar.getRightButton().setOnClickListener(this);
		mActionBar.setShowRightButton(true);

		rootView = inflater.inflate(R.layout.fragment_account_homepage, null);
		findViewById(R.id.account_header_view_avatar).setOnClickListener(this);
		mListView = (ListView) findViewById(android.R.id.list);
		mAdapter = new HomeItemAdapter();
		mListView.setAdapter(mAdapter);
		mListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ItemBeam bean = mItems.get(position);
				if (bean.fragment == AgentActivity.FRAGMENT_ACCOUNT_ORDERS)
					startActivity(AgentActivity.intentForFragment(mActivity,
							bean.fragment).putExtra(Run.EXTRA_VALUE, true));
				else
					startActivity(AgentActivity.intentForFragment(mActivity,
							bean.fragment));
			}
		});
		findViewById(R.id.account_header_view_cover).setOnClickListener(this);
		String username = Run.loadOptionString(mActivity,
				Run.pk_logined_username, "");
		((TextView)findViewById(R.id.account_header_view_mobile)).setText(username);

		mWallpaperPickerView = findViewById(R.id.westore_homepage_wallpaper_pickerview);
		rootView.findViewById(R.id.shop_photo_graph).setOnClickListener(this);
		rootView.findViewById(R.id.shop_photo_album).setOnClickListener(this);
		rootView.findViewById(R.id.westore_homepage_dismiss_pickerview)
				.setOnClickListener(this);

		// 订单页面点击
		findViewById(R.id.account_orders_paying).setOnClickListener(this);
		findViewById(R.id.account_orders_shipping).setOnClickListener(this);
		findViewById(R.id.account_orders_receiving).setOnClickListener(this);
		findViewById(R.id.account_orders_return).setOnClickListener(this);
		findViewById(R.id.account_orders_rating).setOnClickListener(this);
	};

	private void showWallpaperPickerView() {
		mWallpaperPickerView.setVisibility(View.VISIBLE);
		View animView = findViewById(R.id.westore_homepage_bottom_zone);
		Animation animIn = AnimationUtils.loadAnimation(mActivity,
				R.anim.push_up_in);
		animView.startAnimation(animIn);
	}

	private void dismissWallpaperPickerView() {
		View animView = findViewById(R.id.westore_homepage_bottom_zone);
		Animation animOut = AnimationUtils.loadAnimation(mActivity,
				R.anim.push_down_out);
		animOut.setAnimationListener(new SimpleAnimListener() {
			@Override
			public void onAnimationEnd(Animation animation) {
				mWallpaperPickerView.setVisibility(View.GONE);
			}
		});
		animView.startAnimation(animOut);
	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.account_orders_return
				|| v.getId() == R.id.account_orders_receiving
				|| v.getId() == R.id.account_orders_shipping
				|| v.getId() == R.id.account_orders_paying) {
			startActivity(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_ACCOUNT_ORDERS).putExtra(
					Run.EXTRA_VALUE, v.getId()));
		} else if (v.getId() == R.id.account_header_view_avatar) {
			Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
			intent.setType("image/*");
			startActivityForResult(intent, REQUEST_CODE_PICKER_AVATAR);
		} else if (v.getId() == R.id.action_bar_titlebar_right) {
			startActivity(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_ACCOUNT_SETTING));
		} else if (v.getId() == R.id.account_orders_rating) {
			startActivity(AgentActivity.intentForFragment(mActivity,
					AgentActivity.FRAGMENT_ORDER_RATING));
		} else if (v.getId() == R.id.account_home_item_phone) {
			final CustomDialog dialog = new CustomDialog(mActivity);
			dialog.setMessage("确定要拨打客服热线？");
			dialog.setNegativeButton(getString(R.string.cancel),
					new OnClickListener() {

						@Override
						public void onClick(View v) {
							dialog.dismiss();
						}
					})
					.setPositiveButton(getString(R.string.ok),
							new OnClickListener() {

								@Override
								public void onClick(View v) {
									String tel = getString(
											R.string.service_phone).replace(
											"-", "");
									Intent intent = new Intent(
											Intent.ACTION_DIAL, Uri
													.parse("tel:" + tel));
									intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
									startActivity(intent);
								}
							}).setCanceledOnTouchOutside(true).show();
		} else if (v.getId() == R.id.account_header_view_cover) {
			showWallpaperPickerView();
		} else if (v.getId() == R.id.shop_photo_graph) {
			Intent it = new Intent("android.media.action.IMAGE_CAPTURE");
			File file = FileUtils.createHeadFile();
			fileUri = Uri.fromFile(file);
			it.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
			startActivityForResult(it, Activity.DEFAULT_KEYS_DIALER);
			dismissWallpaperPickerView();
		} else if (v.getId() == R.id.shop_photo_album) {
			Intent intent = new Intent();
			intent.setType("image/*");
			intent.putExtra("return-data", true);
			intent.setAction(Intent.ACTION_GET_CONTENT);
			startActivityForResult(intent, Activity.DEFAULT_KEYS_SHORTCUT);
			dismissWallpaperPickerView();
		} else if (v.getId() == R.id.westore_homepage_dismiss_pickerview) {
			dismissWallpaperPickerView();
		}
	}

	private static Uri fileUri = null;

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		fromLoginPage = (requestCode == REQUEST_CODE_USER_LOGIN);

		if (requestCode == REQUEST_CODE_USER_LOGIN
				&& resultCode != Activity.RESULT_OK) {
			MainTabFragmentActivity.mTabActivity.setCurrentTabByIndex(0);
//			fromLoginPage = true;
		} else if (requestCode == REQUEST_CODE_PICKER_AVATAR
				&& resultCode == Activity.RESULT_OK) {
			FileOutputStream fos = null;
			Bitmap bitmap = null;
			try {
				ContentResolver resolver = mActivity.getContentResolver();
				Uri originalUri = data.getData();
				Cursor cursor = resolver.query(originalUri,
						new String[] { Images.Media.DATA }, null, null, null);
				cursor.moveToFirst();
				File originFile = new File(cursor.getString(0));
				if (!originFile.exists())
					return;
				// 图尺寸大小限制
				double size = originFile.length() / 1024.0 / 1024.0;
				if (size > 1) {
					Run.alert(mActivity, R.string.shop_thumb_large_size);
					return;
				}

				bitmap = BitmapFactory.decodeFile(originFile.getAbsolutePath());

				File file = new File(Run.doCacheFolder, "file");
				if (!file.getParentFile().exists())
					file.getParentFile().mkdirs();
				fos = new FileOutputStream(file);
				bitmap.compress(CompressFormat.JPEG, 60, fos);
				fos.flush();
				// 更新到服务器
				JsonTaskHandler handler = null;
				handler = new UpdateWallpaperTask(file, "avatar",
						new JsonRequestCallback() {
							@Override
							public void task_response(String jsonStr) {
								initAccountHeaderView(rootView, mLoginedUser);
							}
						});
				Run.excuteJsonTask(new JsonTask(), handler);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				// 回收资源
				if (bitmap != null)
					bitmap.recycle();
				try {
					if (fos != null)
						fos.close();
				} catch (Exception e) {
				}
			}
		} else if (requestCode == Activity.DEFAULT_KEYS_DIALER) {
			FileOutputStream fos = null;
			File originFile = new File(fileUri.getPath());
			Bitmap bitmap1 = BitmapFactory.decodeFile(fileUri.getPath());
			double size = originFile.length() / 1024.0 / 1024.0;
			if (size > 1) {
				bitmap1 = ThumbnailUtils.extractThumbnail(bitmap1, 720, 1280);
			}
			bitmap = bitmap1;
			File file = new File(Run.doCacheFolder, "file");

			if (!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			try {
				fos = new FileOutputStream(file);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
				fos.flush();
				JsonTaskHandler handler = new UpdateWallpaperTask(file,
						"cover", new JsonRequestCallback() {

							@Override
							public void task_response(String jsonStr) {
								initAccountHeaderView(rootView, mLoginedUser);
							}
						});
				Run.excuteJsonTask(new JsonTask(), handler);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		} else if (requestCode == Activity.DEFAULT_KEYS_SHORTCUT) {
			ContentResolver resolver = mActivity.getContentResolver();
			FileOutputStream fos = null;
			try {
				Uri originalUri = data.getData();
				Cursor cursor = resolver.query(originalUri,
						new String[] { MediaStore.Images.Media.DATA }, null,
						null, null);
				cursor.moveToFirst();
				File originFile = new File(cursor.getString(0));
				Bitmap bitmap1 = BitmapFactory.decodeFile(originFile
						.getAbsolutePath());
				double size = originFile.length() / 1024.0 / 1024.0;
				if (size > 1) {
					// Run.alert(mActivity, R.string.shop_thumb_large_size);
					// return;
					bitmap1 = ThumbnailUtils.extractThumbnail(bitmap1, 720,
							1280);
				}
				bitmap = bitmap1;
			} catch (Exception e) {
				e.printStackTrace();
			}
			File file = new File(Run.doCacheFolder, "file");

			if (!file.getParentFile().exists())
				file.getParentFile().mkdirs();
			try {
				fos = new FileOutputStream(file);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
				fos.flush();
				JsonTaskHandler handler = new UpdateWallpaperTask(file,
						"cover", new JsonRequestCallback() {

							@Override
							public void task_response(String jsonStr) {
								initAccountHeaderView(rootView, mLoginedUser);
							}
						});
				Run.excuteJsonTask(new JsonTask(), handler);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	private Bitmap bitmap = null;

	private class HomeItemAdapter extends BaseAdapter {
		public HomeItemAdapter() {
		}

		@Override
		public int getCount() {
			return mItems.size();
		}

		@Override
		public ItemBeam getItem(int position) {
			return mItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (convertView == null) {
				convertView = mActivity.getLayoutInflater().inflate(
						R.layout.fragment_account_home_item, null);
			}

			convertView.findViewById(R.id.account_home_item_divider)
					.setVisibility(View.VISIBLE);
			convertView.findViewById(R.id.account_home_item_head)
					.setVisibility(View.GONE);
			convertView.findViewById(R.id.account_home_item_tail)
					.setVisibility(View.GONE);
			if (position == 0) {
				convertView.findViewById(R.id.account_home_item_head)
						.setVisibility(View.VISIBLE);
				convertView.findViewById(android.R.id.toggle).setVisibility(
						View.GONE);
				((TextView) convertView.findViewById(R.id.account_home_wallet))
						.setText(walletAccount);
			} else if (position == getCount() - 1) {
				convertView.findViewById(R.id.account_home_item_divider)
						.setVisibility(View.GONE);
				convertView.findViewById(R.id.account_home_item_tail)
						.setVisibility(View.VISIBLE);
				convertView.findViewById(android.R.id.toggle).setVisibility(
						View.VISIBLE);
				((TextView) convertView.findViewById(R.id.account_home_wallet))
						.setText("");
			} else {
				convertView.findViewById(android.R.id.toggle).setVisibility(
						View.VISIBLE);
				((TextView) convertView.findViewById(R.id.account_home_wallet))
						.setText("");
			}

			TextView textview = (TextView) convertView
					.findViewById(android.R.id.text1);
			ImageView iconView = (ImageView) convertView
					.findViewById(android.R.id.icon);
			textview.setText(getItem(position).name);
			if (getItem(position).name == R.string.me_item_help) {
				View view = convertView
						.findViewById(R.id.account_home_item_phone);
				view.setVisibility(View.VISIBLE);
				view.setOnClickListener(AccountHomeFragment.this);
			} else {
				convertView.findViewById(R.id.account_home_item_phone)
						.setVisibility(View.GONE);
			}
			// iconView.setImageResource(getItem(position).icon);
			iconView.setVisibility(View.GONE);

			return convertView;
		}
	}

	private class ItemBeam {
		public int icon;
		public int name;
		public int fragment;

		public ItemBeam(int icon, int name, int fragment) {
			this.icon = icon;
			this.name = name;
			this.fragment = fragment;
		}
	}

//	private class GetOfflineNo implements JsonTaskHandler {
//
//		@Override
//		public void task_response(String json_str) {
//			try {
//				JSONObject all = new JSONObject(json_str);
//				if (Run.checkRequestJson(mActivity, all)) {
//					JSONObject data = all.optJSONObject("data");
//					if (data != null
//							&& !TextUtils.isEmpty(data.optString("CardNo"))) {
//						((ImageView) findViewById(R.id.account_header_view_qrcode))
//								.setImageBitmap(Util.CreateOneDCode(mActivity,
//										data.optString("CardNo")));
//					} else {
//						((ImageView) findViewById(R.id.account_header_view_qrcode))
//								.setImageBitmap(null);
//					}
//				} else {
//					((ImageView) findViewById(R.id.account_header_view_qrcode))
//							.setImageBitmap(null);
//				}
//			} catch (JSONException e) {
//				e.printStackTrace();
//			}
//		}
//
//		@Override
//		public JsonRequestBean task_request() {
//			return new JsonRequestBean(Run.API_URL,
//					"mobileapi.point.offline_point");
//		}
//	}

	private class GetWallet implements JsonTaskHandler {

		@Override
		public void task_response(String json_str) {
			try {
				JSONObject all = new JSONObject(json_str);
				if (Run.checkRequestJson(mActivity, all)) {
					walletAccount = all.optString("data");
					mAdapter.notifyDataSetChanged();
				}
			} catch (JSONException e) {
				e.printStackTrace();
			}
		}

		@Override
		public JsonRequestBean task_request() {
			return new JsonRequestBean(Run.API_URL,
					"mobileapi.member.get_member_wallet");
		}

	}

}
